<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-改纺计划`"
			width="1300px"
			:show-content-loading="showLoading"
			:confirm-btn-loading="saveBtnLoading"
			:show-confirm-btn="pageType !== 'detail'"
			:show-cancel-btn="pageType !== 'detail'"
			:show-close-btn="pageType === 'detail'"
			@on-close="onVisibleChange(false)"
			@on-cancel="onVisibleChange(false)"
			@on-visible-change="onVisibleChange"
			@on-confirm="onConfirmBtn"
		>
			<el-form ref="searchParams" :model="searchParams" :rules="rules" :hide-required-asterisk="pageType === 'detail' || searchParams.auditState === 1" label-width="110px" :show-message="false">
				<div ref="box1">
					<div class="margin-bottom-4 flex-between-center">
						<el-tag class="el-icon-tickets" effect="plain">基本信息</el-tag>
						<jk-button icon="el-icon-printer" size="mini" @click="onPrintBtn">打印</jk-button>
					</div>
					<jk-card>
						<el-row ref="box1" class="flex-start-center-wrap">
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="日期" prop="belongDate">
									<span v-if="pageType === 'detail'" class="read-only-2" placeholder="日期">{{ searchParams.belongDate }}</span>
									<jk-date-picker v-else v-model="searchParams.belongDate" placeholder="日期" size="medium" clearable @change="onItemChange" />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
									<jk-select v-if="pageType === 'detail'" v-model="searchParams.workshopId" style="width: 100%" disabled size="medium" :option-list="workshopList" :clearable="false" placeholder="区域" @change="onItemChange"></jk-select>
									<jk-select v-else v-model="searchParams.workshopId" style="width: 100%" :option-list="workshopList" size="medium" :clearable="false" placeholder="区域" @change="onItemChange"></jk-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="工序" prop="processId">
									<jk-select v-if="pageType === 'detail'" v-model="searchParams.processId" style="width: 100%" disabled :option-list="processList" placeholder="工序" clearable size="medium" @change="onItemChange"></jk-select>
									<jk-select v-else v-model="searchParams.processId" style="width: 100%" :option-list="processList" placeholder="工序" clearable size="medium" @change="onItemChange"></jk-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="单据编号">
									<jk-input v-if="pageType === 'detail'" v-model="searchParams.code" style="width: 100%" :option-list="processList" placeholder="序列号" clearable size="medium"></jk-input>
									<jk-input v-else v-model="searchParams.code" style="width: 100%" :option-list="processList" placeholder="序列号" clearable size="medium"></jk-input>
								</el-form-item>
							</el-col>
							<el-col :span="16">
								<el-form-item class="margin-bottom-0" label="备注">
									<span v-if="pageType === 'detail' || searchParams.auditState === 1" class="read-only-2">{{ searchParams.remark }}</span>
									<el-input v-else v-model="searchParams.remark" :rows="1" type="textarea" placeholder="" />
								</el-form-item>
							</el-col>
						</el-row>
					</jk-card>
				</div>
				<el-tabs type="border-card" class="margin-top-10">
					<el-tab-pane label="改纺机台">
						<span slot="label"><i class="el-icon-box"></i> 改纺机台</span>
						<div ref="box2" class="flex-between-center margin-bottom-4">
							<div class="flex-between-center width-100-percent">
								<div>
									<el-button v-if="pageType === 'detail'" size="mini" disabled type="primary" icon="el-icon-plus" class="" effect="plain">改纺机台</el-button>
									<el-button v-else size="mini" type="primary" :disabled="!searchParams.workshopId || !searchParams.processId" icon="el-icon-plus" class="" effect="plain" @click="addMachine">改纺机台</el-button>
								</div>
								<jk-button type="warning" size="mini" :loading="exportLoading" @click="onReportBtn">导出</jk-button>
							</div>
							<div class="flex-start-center">
							</div>
						</div>
						<jk-table border :data="searchParams.itemList" :height="dialogTableHeight - 90">
							<vxe-column title="打印状态" align="center" field="printerState" :width="74">
								<template slot="header">
									<div style="color: #2d8cf0;cursor: pointer;" @click="onAllPrinter">打印状态</div>
								</template>
								<template slot-scope="scope">
									<el-switch v-model="scope.row.printerState" :disabled="pageType === 'detail' || searchParams.auditState === 1"></el-switch>
								</template>
							</vxe-column>
							<vxe-column :width="70" align="center" title="操作">
								<template slot-scope="scope">
									<el-button :disabled="pageType === 'detail'" icon="el-icon-minus" size="mini" @click="searchParams.itemList.splice(scope.rowIndex, 1)"></el-button>
								</template>
							</vxe-column>
							<vxe-column field="machineName" align="left" :width="70" title="机台"></vxe-column>
							<vxe-column field="preProductName" align="left" :width="140" title="改前品种"></vxe-column>
							<vxe-column title="品种进程" align="left" field="productProgressType" :min-width="100">
								<template slot-scope="scope">
									<jk-select v-model="scope.row.productProgressType" placeholder="品种进程" value-key-name="name" :option-list="productProgressTypeList" size="mini"></jk-select>
								</template>
							</vxe-column>
							<vxe-column title="改纺类型" align="left" field="unitPrice" :min-width="100">
								<template slot-scope="scope">
									<jk-select v-model="scope.row.renovateType" placeholder="改纺类型" value-key-name="name" :option-list="renovateTypeList" size="mini"></jk-select>
								</template>
							</vxe-column>
							<vxe-column field="productName" :min-width="140" title="改纺品种"></vxe-column>
							<!--<vxe-column field="preBatchCode" :min-width="140" title="改前批号"></vxe-column>-->
							<vxe-column title="纸管颜色" align="left" field="paperTubeList" :min-width="80">
								<template slot-scope="scope">
									<span>{{ scope.row.paperTubeList ? scope.row.paperTubeList.map(x => x.name).join(',') : '' }}</span>
								</template>
							</vxe-column>
							<vxe-column title="腰绳颜色" align="left" field="waistPopeList" :min-width="80">
								<template slot-scope="scope">
									<span>{{ scope.row.waistPopeList ? scope.row.waistPopeList.map(x => x.name).join(',') : '' }}</span>
								</template>
							</vxe-column>
							<vxe-column title="标签颜色" align="left" field="unitPrice" :min-width="80">
								<template slot-scope="scope">
									<span>{{ scope.row.labelColorList ? scope.row.labelColorList.map(x => x.name).join(',') : '' }}</span>
								</template>
							</vxe-column>
							<vxe-column field="batchCode" align="left" :min-width="100" title="改纺批号"></vxe-column>
							<vxe-column field="orderSaleQty" align="right" :width="60" title="数量"></vxe-column>
							<vxe-column field="remark" :width="120" title="备注">
								<template slot-scope="scope">
									<el-input v-if="pageType === 'detail'" v-model="scope.row.remark" size="mini" :rows="1" type="textarea" disabled clearable placeholder="请输入内容"></el-input>
									<el-input v-else v-model="scope.row.remark" size="mini" :rows="1" type="textarea" clearable placeholder="请输入内容"></el-input>
								</template>
							</vxe-column>
						</jk-table>

					</el-tab-pane>
					<el-tab-pane label="更多说明">
						<span slot="label"><i class="el-icon-document"></i> 更多说明</span>
						<jk-button icon="el-icon-plus" :disabled="pageType === 'detail'" type="primary" size="mini" class="margin-bottom-4" @click="addCustomRemarkList">添加说明</jk-button>
						<el-row
							v-for="(item, index) in searchParams.customDescription"
							:key="index"
							class="margin-bottom-4"
						>
							<el-col
								:span="24"
								class="flex-start-center"
							>
								<span>{{ index + 1 }}、</span>
								<span v-if="pageType === 'detail' || searchParams.auditState === 1" class="read-only-2">{{ item.illustrate }}</span>
								<jk-input v-else v-model="item.illustrate" class="width-100-percent" placeholder="请输入" size="medium"></jk-input>
							</el-col>
						</el-row>
					</el-tab-pane>
				</el-tabs>
			</el-form>
		</jk-dialog>
		<checkbox-upkeep-item-dialog
			:default-select-rows="searchParams.itemList"
			:data-item="dataItem"
			:dialog-state="checkboxUpkeepItemDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxUpkeepItemDialog"
			@itemList="itemLista"
		></checkbox-upkeep-item-dialog>
	</div>
</template>

<script>
    import { pageConfig, formatDate } from '/src/utils/jk/jk-tool';
    import calHeight from '/src/mixins/cal-dialog-height';
    import { orderPriorityList } from '../../../utils/jk/status-option-list';
    import { creationChangePlan, subitem, getChangePlanPage, updateProduction, productionChangeSpinningPlanGetCode } from '@/api/production/planAlterSpinning';
    import {
        productionPrdNoticeMachineChangePostPage
    } from '../../../api/production/xsRenovateOrder';
    import { openStateList } from '../../../utils/jk/status-option-list';
    import checkboxUpkeepItemDialog from './checkbox-upkeep-item-dialog.vue';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    export default {
        mixins: [calHeight],
        components: { checkboxUpkeepItemDialog },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            },
            request: {
                type: Function,
                require: true,
                default: null
            }
        },
        data() {
            return {
                apiItem: {
                    'page': productionPrdNoticeMachineChangePostPage,
                    'post': creationChangePlan,
                    'postzx': subitem,
                    'exportExcel': null
                },
                exportLoading: false,
                productProgressTypeList: [],
                renovateTypeList: [],
                openStateList: openStateList,
                processList: [],
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                priorityList: orderPriorityList,
                checkboxUpkeepItemDialogState: false,
                rules: {
                    workshopId: [{ required: true, trigger: 'change' }],
                    belongDate: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }]
                },
                loading: false,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    belongDate: '',
                    processCode: '',
                    processId: '', // 生产工序id
                    auditState: null,
                    workshopId: '',
                    workshopName: '', // 生产区域name
                    itemList: [],
                    processName: '', // 生产工序name
                    id: '',
                    customDescription: [],
                    code: ''
                },
                dataItem: {},
                itemList: [],
                isOpen: false
            };
        },
        methods: {
            onReportBtn() {
                const params = this.searchParams ? JSON.parse(JSON.stringify(this.searchParams)) : {};
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                }).then(() => {
                    import('@/vendor/Export2Excel').then(excel => {
                        const tHeader = ['机台', '改前品种', '品种进程', '改纺类型', '改纺品种', '纸管颜色', '腰绳颜色', '标签颜色', '改纺批号', '数量', '备注'];
                        const filterVal = ['machineName', 'preProductName', 'productProgressType', 'renovateType', 'productName', 'paperTubeList', 'waistPopeList', 'labelColorList', 'batchCode', 'orderSaleQty', 'remark'];
                        const list = JSON.parse(JSON.stringify(this.searchParams.itemList)).map(x => {
                            x.paperTubeList = x.paperTubeList ? x.paperTubeList.map(k => k.name).join() : '';
                            x.waistPopeList = x.waistPopeList ? x.waistPopeList.map(k => k.name).join() : '';
                            x.labelColorList = x.labelColorList ? x.labelColorList.map(k => k.name).join() : '';
                            return x;
                        });
                        const data = list.map(v => filterVal.map(j => {
                            return v[j];
                        }));
                        excel.export_json_to_excel({
                            header: tHeader,
                            data,
                            filename: `改纺计划-${this.searchParams.code}`,
                            // filename: `改纺计划-${this.searchParams.belongDate ? this.searchParams.belongDate.replace(/[\-\/\.]/g, '') : ''}`,
                            autoWidth: true,
                            bookType: 'xlsx'
                        });
                        this.exportLoading = false;
                    });
                }).catch(() => {});
            },
            addCustomRemarkList() {
                this.searchParams.customDescription.push(
                    {
                        illustrate: ''
                    }
                );
            },
            onAllPrinter() {
                this.isOpen = !this.isOpen;
                this.searchParams.itemList.forEach(x => {
                    this.$set(x, 'printerState', this.isOpen);
                });
            },
            itemLista(e) {
                e.forEach(x => {
                    this.searchParams.itemList.push(x);
                });
            },
            onVisibleChangeOfCheckboxUpkeepItemDialog(e) {
                this.checkboxUpkeepItemDialogState = e;
            },
            onPrintBtn() {
                this.$emit('on-visible-change', false);
                const routeUrl = this.$router.resolve({
                    name: 'printRenovate',
                    query: {
                        id: this.dataId
                    }
                });
                window.open(routeUrl.href, '_blank');
            },
            onItemChange() {
                this.$set(this.searchParams, 'itemList', []);
            },
            // 改纺机台按钮
            addMachine() {
                this.dataItem = {
                    processId: this.searchParams.processId,
                    workshopId: this.searchParams.workshopId
                };
                this.checkboxUpkeepItemDialogState = true;
            },
            // 拼参数
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                if (!this.dataId) {
                    params.auditState = 1;
                    params.id = this.dataId;
                }
                params.id = this.dataId;
                const processItem = this.processList.find(x => x.id === params.processId);
                params.processName = processItem.name;
                params.processCode = processItem.code;
                const workshopItem = this.workshopList.find(k => k.id === params.workshopId) || {};
                params.workshopName = workshopItem.name;
                params.workshopCode = workshopItem.code;
                return params;
            },
            // 弹窗确定
            onConfirmBtn() {
                this.$refs['searchParams'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                if (!this.dataId) {
                    this.saveBtnLoading = true;
                    this.apiItem.post(this.getParamData()).then(res => {
                        this.saveBtnLoading = false;
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.$emit('on-visible-change', false);
                            this.request();
                        }
                    });
                } else {
                    updateProduction(this.getParamData()).then(res => {
                        this.saveBtnLoading = false;
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.$emit('on-visible-change', false);
                            this.request();
                        }
                    });
                }
            },
            // 当月序列号
            getSerialNumber() {
                productionChangeSpinningPlanGetCode({}).then(res => {
                    if (res.data.status === 200) {
                        this.$set(this.searchParams, 'code', res.data.res);
                    }
                });
            },
            // 弹窗开关
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        // this.$refs['searchParams'].resetFields();
                    });
                }
            },
            getDetailRequest() {
                return getChangePlanPage({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.searchParams.itemList = res.data.res.itemList;
                        this.$set(this.searchParams, 'code', res.data.res.code);
                        this.$set(this.searchParams, 'belongDate', res.data.res.belongDate);
                        this.$set(this.searchParams, 'workshopId', res.data.res.workshopId);
                        this.$set(this.searchParams, 'processId', res.data.res.processId);
                        this.$set(this.searchParams, 'remark', res.data.res.remark);
                        this.$set(this.searchParams, 'customDescription', res.data.res.customDescription);
                    }
                });
            },
            // 获取品种进程
            getProductProgressRequest() {
                return systemBusinessDictPage({
                    categoryCode: 'RENOVATE_PRODUCT_PROGRESS'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.productProgressTypeList = res.data.res || [];
                    }
                });
            },
            // 获取改纺类型
            getRenovateTypeDataRequest() {
                return systemBusinessDictPage({
                    categoryCode: 'RENOVATE_TYPE'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.renovateTypeList = res.data.res || [];
                    }
                });
            },
            // 页面展示工序，区域
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.processList = this.$store.state.user.userProcess.processList || [];
                await this.getProductProgressRequest();
                await this.getRenovateTypeDataRequest();
                if (!this.dataId) this.getSerialNumber();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                    // 进入页面直接给选择框赋值
                    this.searchParams.belongDate = formatDate(Date.now());
                    if (!this.searchParams.processId) {
                        this.$set(this.searchParams, 'processId', this.$store.state.user.userProcess.defaultProcessId);
                    }
                    if (!this.searchParams.workshopId) {
                        this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                    }
                    this.$nextTick(() => {
                        this.$refs['searchParams'].clearValidate();
                    });
                }
            }
        }
    };
</script>
